package com.work.lxykeeper.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.work.lxykeeper.base.BaseApplication;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author Created by WZ on 2015年12月25日
 */
public class GlobalUtils {
	// 手机网络类型
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;

	/**
	 * 获取当前网络类型
	 * @return 0：没有网络 1：WIFI网络 2：W`AP网络 3：NET网络
	 */
	public static int getNetworkType() {
		int netType = 0;
		ConnectivityManager connectivityManager = (ConnectivityManager) UIUtils
				.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			if (!StringUtils.isEmpty(extraInfo)) {
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}

	/**
	 * 四舍五入保留两位小数点
	 * 
	 * @param number
	 *            需要处理的数
	 * @param scale
	 *            保留小数点的位数
	 * @return
	 */
	public static double keepTwoSecimal(double number, int scale) {
		BigDecimal b = new BigDecimal(number);
		return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 四舍五入保留两位小数点
	 * 
	 * @param numberStr
	 *            需要处理的数
	 * @param scale
	 *            保留小数点的位数
	 * @return
	 */
	public static double keepTwoSecimal(String numberStr, int scale) {
		double number = Double.parseDouble(numberStr);
		BigDecimal b = new BigDecimal(number);
		return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 返回当前程序版本name
	 */
	public static String getAppVersionNames() {
		Context context = BaseApplication.getContext();
		String versionName = "";
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			// Log.e("VersionInfo", "Exception", e);
		}
		return versionName;
	}

	/**
	 * 判断是否是标准手机号
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^(?:13\\d|15[0-9]|14[0-9]|17[0-9]|18[0-9])-?\\d{5}(\\d{3}|\\*{3})$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

}
